using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class MonsterObj : TankBase
{
    //目标点
    private Transform target;

    //随机点数组
    public Transform[] randArr;

    //看向的目标----玩家位置
    public Transform lookTransform;

    //开火距离
    public float fireDis = 5f;

    //开火间隔
    public float fireTime = 1f;

    public float nowTime = 0;

    public Transform[] shootPos;

    public GameObject bullet;

    private Rect bgRect;
    private Rect hpRect;

    public Texture bgTexture;
    public Texture hpTexture;

    private float showTime = 0;

    // Start is called before the first frame update
    void Start()
    {
        SetTarget();
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.LookAt(target);
        this.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
        if (Mathf.Abs(Vector3.Distance(this.transform.position, this.target.position)) < 0.05f)
        {
            SetTarget();
        }

        if (Vector3.Distance(this.transform.position, lookTransform.position) <= fireDis)
        {
            nowTime += Time.deltaTime;
            if (nowTime >= fireTime)
            {
                Fire();
                nowTime = 0;
            }
        }


        if (Vector3.Distance(this.transform.position, lookTransform.position) < 10f)
        {
            turretObject.LookAt(lookTransform);
        }
        else
        {
            turretObject.LookAt(target);
        }
    }

    public void SetTarget()
    {
        int index = Random.Range(0, randArr.Length);
        target = randArr[index];
    }

    public override void Fire()
    {
        for (var i = 0; i < shootPos.Length; i++)
        {
            GameObject bulletObj = Instantiate(bullet, shootPos[i].position, shootPos[i].rotation);
            //控制子弹的操作
            BulletObj component = bulletObj.GetComponent<BulletObj>();
            component.SetOwn(this);
        }
    }

    public override void DestroyTank()
    {
        base.DestroyTank();
        GamePanel.Instance.AddScore(10);
    }


    private void OnGUI()
    {
        if (showTime > 0)
        {
            //近大远小  如果用z来完成
            showTime -= Time.deltaTime;
            Vector3 screenPoint = Camera.main.WorldToScreenPoint(this.transform.position);
            screenPoint.y = Screen.height - screenPoint.y;

            bgRect.x = screenPoint.x - 50;
            bgRect.y = screenPoint.y - 50;
            bgRect.width = 100;
            bgRect.height = 15;
            GUI.DrawTexture(bgRect, bgTexture);

            hpRect.x = screenPoint.x - 50;
            hpRect.y = screenPoint.y - 50;
            hpRect.width = (float)hp / maxHp * 100;
            hpRect.height = 15;
            GUI.DrawTexture(hpRect, hpTexture);
        }
    }

    public override void Hurt(TankBase other)
    {
        base.Hurt(other);
        showTime = 3;
    }
}